<template>
  <div class="container">
    <a-card class="chat-card">
      <template #title>系统功能介绍助手</template>
      <div class="chat-container">
        <div class="chat-messages" ref="messageContainer">
          <div v-for="(msg, index) in messages" :key="index" :class="msg.role">
            <a-avatar
              :style="{
                backgroundColor:
                  msg.role === 'assistant' ? '#165DFF' : '#00B42A'
              }"
            >
              {{ msg.role === 'assistant' ? 'AI' : '我' }}
            </a-avatar>
            <div class="message-content">
              <a-typography-paragraph>{{ msg.content }}</a-typography-paragraph>
            </div>
          </div>
        </div>
        <div class="chat-input">
          <a-space direction="vertical" fill>
            <a-input-search
              v-model="inputMessage"
              placeholder="请输入您想了解的功能..."
              button-text="发送"
              :loading="loading"
              search-button
              @press-enter="sendMessage"
              @search="sendMessage"
            />
            <div class="quick-questions">
              <a-space>
                <a-tag
                  v-for="q in quickQuestions"
                  :key="q"
                  clickable
                  @click="() => handleQuickQuestion(q)"
                >
                  {{ q }}
                </a-tag>
              </a-space>
            </div>
          </a-space>
        </div>
      </div>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { Message } from '@arco-design/web-vue';
import { chatWithGptUsingPost } from '@/service/gpt/api';

interface ChatMessage {
  role: 'user' | 'assistant';
  content: string;
}

const loading = ref(false);
const messages = ref<ChatMessage[]>([
  {
    role: 'assistant',
    content:
      '你好！我是系统AI助手，可以为您介绍系统的各项功能。您可以直接提问，或点击下方的快捷问题。'
  }
]);

const quickQuestions = [
  '系统有哪些主要功能？',
  '如何使用签到功能？',
  '如何管理用户权限？'
];

const inputMessage = ref('');
const messageContainer = ref<HTMLElement | null>(null);

const handleQuickQuestion = (question: string) => {
  inputMessage.value = question;
  sendMessage();
};

const sendMessage = async () => {
  if (!inputMessage.value.trim() || loading.value) return;

  // 添加用户消息
  messages.value.push({
    role: 'user',
    content: inputMessage.value
  });

  // 先添加一个空的助手消息
  messages.value.push({
    role: 'assistant',
    content: ''
  });

  const currentQuestion = inputMessage.value;
  inputMessage.value = '';
  scrollToBottom();

  loading.value = true;
  try {
    // 调用实际的 GPT API
    const fullResponse = await callGptApi(currentQuestion);

    // 流式输出文字
    await streamText(fullResponse);
  } catch (error) {
    Message.error('请求失败，请重试');
    // 移除空消息
    messages.value.pop();
  } finally {
    loading.value = false;
    scrollToBottom();
  }
};

// 调用 GPT API
const callGptApi = async (message: string) => {
  try {
    const response = await chatWithGptUsingPost({
      prompt: message
    });

    if (response && response.choices && response.choices.length > 0) {
      const firstChoice = response.choices[0];
      if (firstChoice.message && firstChoice.message.content) {
        return firstChoice.message.content;
      }
    }
    throw new Error('API 返回数据格式不正确');
  } catch (error) {
    console.error('API 调用失败:', error);
    return '抱歉，我暂时无法回答这个问题。请稍后再试。';
  }
};

// 模拟流式输出文字
const streamText = async (text: string) => {
  const assistantMessageIndex = messages.value.length - 1;
  const chars = text.split('');

  for (let i = 0; i < chars.length; i++) {
    // 更新最后一条消息的内容
    messages.value[assistantMessageIndex].content += chars[i];

    // 控制打字速度
    await new Promise(resolve => setTimeout(resolve, 20 + Math.random() * 30));

    // 每添加一个字符就滚动到底部
    if (i % 3 === 0) {
      scrollToBottom();
    }
  }
};

// 模拟 GPT 响应
const mockGptResponse = async (message: string) => {
  return new Promise(resolve => {
    setTimeout(() => {
      const responses: Record<string, string> = {
        '系统有哪些主要功能？':
          '本系统主要包含以下功能：\n1. 用户签到打卡\n2. 权限管理\n3. 数据统计\n4. 系统设置',
        '如何使用签到功能？':
          '签到功能使用步骤：\n1. 点击左侧菜单"签到记录"\n2. 在日历界面查看签到状态\n3. 未来日期不可签到\n4. 当天可进行签到操作',
        '如何管理用户权限？':
          '权限管理步骤：\n1. 管理员可以设置用户角色\n2. 不同角色拥有不同的功能权限\n3. 可以自定义角色权限'
      };
      resolve(
        responses[message] ||
          '抱歉，我暂时无法回答这个问题。请尝试其他问题或换个方式提问。'
      );
    }, 1000);
  });
};

const scrollToBottom = () => {
  if (messageContainer.value) {
    setTimeout(() => {
      messageContainer.value!.scrollTop = messageContainer.value!.scrollHeight;
    }, 100);
  }
};

onMounted(() => {
  scrollToBottom();
});
</script>

<style scoped lang="less">
.container {
  padding: 20px;
}

.chat-card {
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;

  :deep(.arco-card-body) {
    flex: 1;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }
}

.chat-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  padding-bottom: 140px; // 为底部输入框留出空间

  .user,
  .assistant {
    display: flex;
    align-items: flex-start;
    margin-bottom: 20px;
    gap: 12px;

    .message-content {
      padding: 16px;
      border-radius: 12px;
      max-width: 80%;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
      }

      :deep(.arco-typography) {
        margin-bottom: 0;
        white-space: pre-line;
      }
    }
  }

  .assistant {
    .message-content {
      background-color: var(--color-fill-2);
      border-bottom-left-radius: 4px;
      position: relative;

      &::before {
        content: '';
        position: absolute;
        left: -8px;
        bottom: 0;
        width: 16px;
        height: 16px;
        background: var(--color-fill-2);
        clip-path: polygon(0 0, 100% 100%, 100% 0);
      }
    }
  }

  .user {
    flex-direction: row-reverse;

    .message-content {
      background-color: var(--color-fill-2);
      color: white;
      border-bottom-right-radius: 4px;
      position: relative;

      &::before {
        content: '';
        position: absolute;
        right: -8px;
        bottom: 0;
        width: 16px;
        height: 16px;
        background-color: var(--color-fill-2);
        clip-path: polygon(0 100%, 0 0, 100% 0);
      }
    }
  }
}

.chat-input-wrapper {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: var(--color-bg-2);
}

.chat-input {
  padding: 20px;
  border-top: 1px solid var(--color-border);
  background-color: var(--color-bg-2);
  position: sticky;
  bottom: 0;
}

.quick-questions {
  margin-top: 8px;

  :deep(.arco-tag) {
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
  }
}
</style>
